package com.listen.service.DB;

import com.listen.common.*;
import com.listen.model.User;
import com.listen.vo.HeadParmsVO;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 建造师必修听课考试
 * */
public class JianZaoShiBixiuDB8049 {
	private static final Logger log = LoggerFactory.getLogger(JianZaoShiBixiuDB8049.class);
	private String cookie;
	private String userid;
	private String info;
	private String urlprefix;
	private static String __viewstate="";
	private static String __viewstategenerator="C2EE9ABB";
	private static String __eventvalidation="";
	private Map<String,Object> resultMap = LoadNewDaAn.resultMap;
	private String[] result1;
	private String[] result2;
	private String[] result3;
	private String panduan;
	private String danxuan;
	private String duoxuan;
	private String Pwr="";
	private String Qwr="";
	private String Hwr="";
	private int flag;
	private ConcurrentHashMap<String, Object>  msgMap = null;
	private Map<String,String> rightResult = new HashMap<>();
	private HttpClientProxy instance = new HttpClientProxy();
	private CloseableHttpResponse response = null;
	private CloseableHttpClient httpClient = null;
	private String proxyInfo = null;

	public static void main(String args[]) throws InterruptedException{
		IPProxyNew proxy = new IPProxyNew(null);
		JianZaoShiBixiuDB8049 bixiu = new JianZaoShiBixiuDB8049();
		User user = new User();
		user.setCode("360403197906050616");
		user.setZy("JB1");//JB1房建工程，JB2市政工程，JB3机电工程
		user.setAllNum(59);
		user.setZyName("二级建造师市政工程必修");
		user.setPassword("888888");
		user.setAddress("http://139.199.171.22:8049/");
		user.setStatus(1);
		for(int i=3;i<=59;i++) {
			Integer num = user.getNowNum();

			if(num < 0)
				i--;
				user.setNowNum(i);
			//String ip = proxy.getOneIpAndPort();
			Map<String,Object> map = bixiu.startListen(user,null);
			/*if(map!=null&&"1".equals(map.get("successFlag"))) {
				break;
			}*/
			Thread.sleep(2000);
		}
	}

	public Map<String,Object> startListen(User user,String ip){
		this.proxyInfo = ip;
		msgMap = new ConcurrentHashMap<>();
		msgMap.put("successFlag", "0");
		msgMap.put("dayNum", "0");
		msgMap.put("addNum", "0");
		if(user.getStatus()==1)
			this.flag = 1;
		//状态为2已听完课，flag=3直接考试
		if(user.getStatus()==2)
			this.flag = 3;
		try {
			toLoginPage(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msgMap;
	}
	//处理get方式的跳转，并解析跳转后的页面
	private void toLoginPage(User user){
		String zyStr = user.getZy();
		String zy = zyStr.substring(2);
		this.urlprefix = user.getAddress();
		String jsoupUrl = urlprefix +"/Login.aspx?ZY="+zy;
		try {
			response = instance.sendHttpGet(httpClient, jsoupUrl, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				this.setCommonParms(html);//设置登录参数
				this.login(jsoupUrl,user);//执行登录操作
			}else{
				print(user.getZyName()+"-"+user.getCode()+"-解析页面参数失败");
			}
		} catch (Exception e) {
			user.setNowNum(-1);
			printError(user.getZyName()+"-"+user.getCode()+"-解析页面参数异常"+e);
		}finally {
			instance.closeResource(response, httpClient);
		}
	}

	//登录
	private void login(String url,User user){
		String code = user.getCode();
		Map<String, String> maps = new HashMap<String, String>();
        maps.put("__VIEWSTATE", __viewstate);
        maps.put("__VIEWSTATEGENERATOR", __viewstategenerator);
        maps.put("__EVENTVALIDATION",__eventvalidation);
        maps.put("txtUserName",code);
        maps.put("txtPwd",user.getPassword());
        maps.put("ddlType", "2");//学员登录
        maps.put("btnLogin", "");
        maps.put("txtLoginName", "");
        maps.put("txtDM", "");
        maps.put("txtFR", "");
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        try {
        	HeadParmsVO head = new HeadParmsVO();
	        head.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			head.setContentType("application/x-www-form-urlencoded");
			response = instance.sendHttpPost(httpClient, head, url, maps, proxyInfo);

        	int state = response.getStatusLine().getStatusCode();
        	if(state == 302||state==200){
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String sessionId = hearders[0].getValue();
        		this.cookie = sessionId.substring(0, sessionId.indexOf(";") + 1);
        		String userIdCookie = hearders[1].getValue();
        		this.userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		String infoCookies = hearders[2].getValue();
        		this.info = infoCookies.substring(0, infoCookies.indexOf(";"));

        		this.cookie = cookie + userid + info;
        		if(flag==3){//只考试
        			buildPaper(user);
        		}else if(flag < 3 ){
                    updateVidoSate(user);//听课，考试
        		}else{
        			print(user.getZyName()+"-"+user.getCode()+"-登录成功后跳转标识异常-flag="+flag);
        			logout(user);
        		}
        	}else{
        		print(user.getZyName()+"-"+user.getCode()+"-登录失败--->"+state);
        		logout(user);
        	}
		} catch (Exception e) {
			printError(user.getZyName()+"-"+user.getCode()+"-登录异常--->"+e);
		}finally{
			instance.closeResource(response, httpClient);
		}
	}

	public void updateStudyType(User user){
        int i = user.getNowNum();
        String id3 = i < 10 ? "0000"+i : "000"+i;
        int number = (int)(40+Math.random()*(60-40+1));
        String Start = DateFormatUtil.getDateAnyMinuteBeforeStr(number);
        Start = Start.replaceAll(" ", "+").replaceAll(":", "%3a");
        String uid = this.userid.substring(userid.indexOf("=")+1, userid.length()-1);

        String cookie = this.cookie +" id3="+id3 + "; Start=" + Start +";checkUid="+uid +"; url=http://139.199.171.22:8049/StudentClass3/WatchVideo3.aspx?ids="+id3 + ";nowtime=2517;totaltime=2547;";
        user.setCookie(cookie);
	    String param = "{RVCode:\"+ i +\"}";
	    String url = this.urlprefix + "/StudentClass3/WatchVideo3.aspx/UpdateStudyType?dt="+DateFormatUtil.getDateEN(new Date());
        HeadParmsVO head = new HeadParmsVO();
        head.setAccept("application/json, text/javascript, */*; q=0.01");
        head.setAcceptEncoding("gzip, deflate");
        head.setAcceptLanguage("zh-CN,zh;q=0.9,en;q=0.8");
        head.setConnection("keep-alive");
        head.setContentType("application/json; charset=UTF-8");
        head.setCookie(cookie);
        head.setHost("139.199.171.22:8049");
        head.setOrigin("http://139.199.171.22:8049");
        head.setReferer("http://139.199.171.22:8049/StudentClass3/WatchVideo3.aspx?ids"+id3);
        head.setxRequestedWith("XMLHttpRequest");
        response = instance.sendHttpPost(httpClient, head, url, param, null);
        int state = response.getStatusLine().getStatusCode();
        try {
            if (state == 200){
                String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(entityStr);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

	//听课，修改视频状态
	private void updateVidoSate(User user){
		String code = user.getCode();
		String zyName = user.getZyName();
		String urls = "";
		int i = user.getNowNum();
		try {
			String id = i < 10 ? "0000"+i : "000"+i;

			int number = (int)(40+Math.random()*(60-40+1));
			String Start = DateFormatUtil.getDateAnyMinuteBeforeStr(number);
			Start = Start.replaceAll(" ", "+").replaceAll(":", "%3a");
			String uid = this.userid.substring(userid.indexOf("=")+1, userid.length()-1);
			String cookie = this.cookie +";checkUid="+uid+";id="+id+";Start="+ Start +";PC1=%u6210%u529F; PC2=%u6210%u529F; PC3=%u6210%u529F; PC4=%u6210%u529F;nowtime=2325;totaltime=2360;";
			urls = this.urlprefix+"/EntpClass/Xtyl.ashx?classid="+i+"&uid="+uid;
			HeadParmsVO head = new HeadParmsVO();
			head.setAccept("*/*");
			head.setContentType("application/json; charset=utf-8");
			head.setCookie(cookie);
			head.setxRequestedWith("XMLHttpRequest");
			response = instance.sendHttpPost(httpClient, head, urls, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				msgMap.put("successFlag", "1");
				msgMap.put("dayNum", "1");
				msgMap.put("addNum", "1");
				print(zyName+"-"+ code +"-第"+i +"个视频成功播放完");
				if(user.getAllNum()==i){
					user.setStatus(2);
				}

			}else{
				print(zyName+"-"+ code +"-第"+i +"个视频播放失败--state="+state);
			}
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
			printError(zyName+"-"+ code +" 第"+i +"个视频"+e);
		}finally{
			instance.closeResource(response, httpClient);

		}
		if(flag==2)//听课并考试
			buildPaper(user);
		else//只听课，听完退出登录
			logout(user);

	}
	//生成考试试卷
	private void buildPaper(User user){
		try {
			//第一步：生成试卷
			String path = this.urlprefix+"/TR_TestPaper3.aspx?id=1";
			//设置请求参数和cookie
			String cookie = this.cookie + this.userid + this.info;
			HeadParmsVO heads = new HeadParmsVO();
			heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			heads.setCookie(cookie);
			response = instance.sendHttpPost(httpClient, heads, path, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == HttpStatus.SC_OK){
				//第二步：解析HTML,获取题目id
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("_thid");
			    this.panduan = parm1.attr("value");
				System.out.println(panduan);
			    Element parm2 = document.getElementById("Hidden1");
			    this.danxuan = parm2.attr("value");
				System.out.println(danxuan);
			    Element parm3 = document.getElementById("Hidden2");
			    this.duoxuan = parm3.attr("value");
				System.out.println(duoxuan);

				//设置题序数组
				/*String[] tixu = (panduan + danxuan + duoxuan).split(",");
				String[] daan = new String[80];
				for (int i = 0;i < 80; i++){
					//判断题默认对
					if (i < 30){
						daan[i] = "Yes";
							this.Pwr += "Yes,";
					}
					//单选题默认A
					if (i >= 30 && i < 60){
						daan[i] = "A";
						this.Qwr += "A,";
					}

					//多选题默认A|B|C|D|E|
					if (i >= 60){
						daan[i] = "A|B|C|D|0";
						this.Hwr += "A|B|C|D|0,";
					}
				}*/

			    this.result1 = (panduan.substring(0, panduan.length()-1)).split(",");
			    this.result2 = (danxuan.substring(0, danxuan.length()-1)).split(",");
			    this.result3 = (duoxuan.substring(0, duoxuan.length()-1)).split(",");

				//提交试卷
				String result = testOnline(user);
				System.out.println(result);

				/*String daans = Pwr + Qwr + Hwr;
				System.out.println(daans);
				//设置答案数组
				String scores[] = result.split("\\|");
				for(int i = 0;i < 50;i++){
					String score = scores[i];
					String tixuhao = tixu[i];
					String rightDaan = daan[i];
					//正确答案
					//判断题
					if ("1".equals(score)){
						System.out.println(tixuhao+"	"+rightDaan);
						//rightResult.put(tixuhao,rightDaan);
					}
				}*/

			}else{
				print(user.getZyName()+"-"+user.getCode()+"-生成试卷失败--->"+state);
			}
		}catch(Exception e){
			printError(user.getZyName()+"-"+user.getCode()+"-生成试卷异常--->"+e);
		}finally {
			instance.closeResource(response, httpClient);
		}

	}
	//提交考试试卷
	private String testOnline(User user){
		String code = user.getCode();
		String zyName = user.getZyName();
		try {
			//设置答案
			this.setParmsValue();
			String cookie = this.cookie + this.userid + this.info;
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("Pid", this.panduan));
	        params.add(new BasicNameValuePair("Qid", this.danxuan));
	        params.add(new BasicNameValuePair("Hid",this.duoxuan));
	        params.add(new BasicNameValuePair("Pwr",this.Pwr));
	        params.add(new BasicNameValuePair("Qwr",this.Qwr));
	        params.add(new BasicNameValuePair("Hwr", this.Hwr));
	        params.add(new BasicNameValuePair("AlNums", "0"));

	        //要传递的参数.
	        String url = this.urlprefix+"/MarkTJ3.aspx?" + URLEncodedUtils.format(params,"UTF-8");
	        HeadParmsVO heads = new HeadParmsVO();
			heads.setAccept("*/*");
			heads.setReferer("http://139.199.171.22:8049/TR_TestPaper.aspx?id=1");
			heads.setCookie(cookie);
			heads.setxRequestedWith("XMLHttpRequest");
			response = instance.sendHttpGet(httpClient, heads, url, proxyInfo);
	        int state = response.getStatusLine().getStatusCode();
	        if (state == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String resultStr = EntityUtils.toString(entity, "UTF-8");
				 System.out.println(resultStr);
                //String score = resultStr.substring(0,resultStr.indexOf("|"));
                //print(zyName+"-"+ code +"-考试成功，本次考试成绩为："+score+"分");
                msgMap.put("successFlag", "1");
                user.setStatus(3);
                return resultStr;
            }else{
            	print(zyName+"-"+ code +"-试卷提交失败！------->state="+state);
            }
		} catch (Exception e) {
			printError(zyName+"-"+code+"-生成试卷异常--->"+e);
		}finally {
			instance.closeResource(response, httpClient);
			//HttpClientUtil.getInstance().closeResource(response);
			//退出登录
			logout(user);
        }
		return null;
	}

	//退出登录
	private void logout(User user){
		try {
			String path = this.urlprefix+"/Public/Logout.aspx";
			//httpGet = new HttpGet(path);
			String cookie = this.cookie + this.userid + this.info +"totaltime=2281; checkUid=38060; nowtime=2281";
			HeadParmsVO heads = new HeadParmsVO();
			heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			heads.setCookie(cookie);
			//httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			//httpGet.setHeader("Cookie", cookie);
			//response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			response = instance.sendHttpGet(httpClient, path, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				//print("退出登录成功!");
			}else{
				//print("退出登录失败!");
			}
		} catch (Exception e) {
			System.out.println("退出登录异常--->");
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//设置登录参数
	private void setCommonParms(String html){
		Document document = Jsoup.parse(html);
	    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
	    __viewstategenerator = parm1.attr("value");
	    Element parm2 = document.getElementById("__EVENTVALIDATION");
	    __eventvalidation = parm2.attr("value");
	    Element parm3 = document.getElementById("__VIEWSTATE");
	    __viewstate = parm3.attr("value");
	}
	
	private void setParmsValue(){
		//设置判断题答案
		for(int i=0;i<this.result1.length;i++){
			String pid = "P"+this.result1[i];
			String panswer = (String) this.resultMap.get(pid);
			if(!"Yes".equalsIgnoreCase(panswer)&&!"No".equalsIgnoreCase(panswer)){
				panswer = "Yes";
			}
			Pwr += panswer + ",";
		}
		System.out.println(Pwr);
		//设置单选题答案
		for(int i=0;i<this.result2.length;i++){
			String pid = "Q"+this.result2[i];
			String panswer = (String) resultMap.get(pid);
			if(!"A".equalsIgnoreCase(panswer)&&!"B".equalsIgnoreCase(panswer)
					&&!"C".equalsIgnoreCase(panswer)&&!"D".equalsIgnoreCase(panswer)){
				panswer = "C";
			}
			Qwr += panswer+",";
		}
		System.out.println(Qwr);
		//设置多选题答案
		for(int i=0;i<this.result3.length;i++){
			String pid = "H"+this.result3[i];
			String panswer = (String) resultMap.get(pid);
			if(panswer==null || panswer.trim().equals("")){
				panswer = "A|B|C|D|0";
			}
			Hwr += panswer +",";
		}

		System.out.println(Hwr);
	}
	
	private void print(String msg){
		msgMap.put("msg", msg);
		log.info(msg);
	}
	
	private void printError(String errMsg){
		msgMap.put("errMsg", errMsg);
		log.error(errMsg);
	}
}
